package com.taotie.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.taotie.constant.MessageConstant;
import com.taotie.constant.OrdersConstant;
import com.taotie.context.BaseContext;
import com.taotie.dto.*;
import com.taotie.entity.*;
import com.taotie.exception.AddressBookBusinessException;
import com.taotie.exception.OrderBusinessException;
import com.taotie.exception.ShoppingCartBusinessException;
import com.taotie.mapper.*;
import com.taotie.result.PageResult;
import com.taotie.service.OrderService;
import com.taotie.utils.WeChatPayUtil;
import com.taotie.vo.OrderPaymentVO;
import com.taotie.vo.OrderStatisticsVO;
import com.taotie.vo.OrderSubmitVO;
import com.taotie.vo.OrderVO;
import com.taotie.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //首先判断收获地址与购物车是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        //通过用户id查询购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        //用随机生成的UUID拼接用户id作为订单号
        UUID uuid = UUID.randomUUID();
        order.setNumber(uuid.toString() + userId);
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细表操作
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
        return orderSubmitVO;

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "饕餮外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        //用orders查询对应的订单详情
        if (orders != null && !orders.isEmpty()) {

            for (Orders order : orders) {
                Long orderId = order.getId();
                //查询出订单详情表的信息并封装到集合中
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(orders.getTotal(), orderVOList);
    }


    @Override
    public OrderVO getOrderDetailById(Long id) {
        //根据传进来的订单id查询订单详情信息
        Orders order = orderMapper.getById(id);
        //根据传进来的订单id查询订单详情信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        //根据id查询订单状态
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Integer orderStatus = order.getStatus();
        //商家接单或派送中则需要致电商家才可修改
        if (OrdersConstant.RECEIVED_ORDER.equals(orderStatus)
                || OrdersConstant.OUT_OF_DELIVERY.equals(orderStatus)) {
            throw new OrderBusinessException(MessageConstant.PLEASE_CALL_THE_MERCHANT);
        }
        //待支付状态，用户可直接取消订单
        if (OrdersConstant.DUE.equals(orderStatus)) {
            //将状态改为取消
            order.setStatus(OrdersConstant.CANCELLED);
        }

        //接单状态下取消订单，需要给用户退款
        if (OrdersConstant.PENDING_ORDER.equals(orderStatus)) {
            refund(order);
        }
        //设置用户取消原因
        order.setCancelReason(MessageConstant.USER_CANCELLATION);
        //设置订单取消时间
        order.setCancelTime(LocalDateTime.now());
        //将用户订单状态改为 “取消订单”
        order.setStatus(OrdersConstant.CANCELLED);
        //调用mapper，统一修改订单状态
        orderMapper.update(order);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //根据订单号查询原本订单信息
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Long orderId = order.getId();
        //取出原订单菜品信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
        if (orderDetailList == null || orderDetailList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.ORDER_NO_MENU_INFORMATION);
        }

        //调用mapper，将 orderDetailList 的菜品信息遍历并添加到shoppingCart
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setDishId(orderDetail.getDishId());
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setSetmealId(orderDetail.getSetmealId());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 管理端进行订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        //搜索内容为空则提示未找到相关订单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //用orders获取List
        List<Orders> ordersList = orders.getResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        //遍历orderList,用orderList中的Orders对象获取到OrderDetails对象
        for (Orders order : ordersList) {
            Long orderId = order.getId();
            //通过orderId查询订单详情
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
            //创建OrderVO对象，将属性拷到orderVO中，再封装到集合
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }

        return new PageResult(orders.getTotal(), orderVOList);
    }

    /**
     * 查询各个状态的订单数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //待接单数量
        Integer pendingOrder = orderMapper.countStatus(OrdersConstant.PENDING_ORDER);
        //待派送数量
        Integer receivedOrder = orderMapper.countStatus(OrdersConstant.RECEIVED_ORDER);
        //派送中数量
        Integer outOfDelivery = orderMapper.countStatus(OrdersConstant.OUT_OF_DELIVERY);

        //封装到OrderStatisticsVO中
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(pendingOrder);
        orderStatisticsVO.setConfirmed(receivedOrder);
        orderStatisticsVO.setDeliveryInProgress(outOfDelivery);
        return orderStatisticsVO;
    }

    /**
     * 商家接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //获取dto中封装的id
        Long id = ordersConfirmDTO.getId();
        Orders order = orderMapper.getById(id);
        //保证订单存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //status只有在“待接单”时才能接单
        if (!OrdersConstant.PENDING_ORDER.equals(order.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //调用mapper将status字段改为3（接单）
        orderMapper.confirm(id);
    }

    /**
     * 商家拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    @Transactional
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //获取订单id
        Long orderId = ordersRejectionDTO.getId();
        //获取商家拒单原因
        String rejectionReason = ordersRejectionDTO.getRejectionReason();
        //订单状态只有在“待接单”时才可以拒单
        Orders order = orderMapper.getById(orderId);
        if (order == null || !OrdersConstant.PENDING_ORDER.equals(order.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //如果用户已经支付则要为用户退款
        if (OrdersConstant.HAVE_PAID.equals(order.getPayStatus())) {
            refund(order);
        }

        //将订单状态修改为“已取消”
        order.setStatus(OrdersConstant.CANCELLED);
        //商家指定拒单原因
        order.setRejectionReason(rejectionReason);
        //设置订单取消时间
        order.setCancelTime(LocalDateTime.now());
        //完成修改
        orderMapper.update(order);

    }

    /**
     * 商家取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //获取订单id
        Long orderId = ordersCancelDTO.getId();
        //获取取消原因
        String cancelReason = ordersCancelDTO.getCancelReason();
        //根据订单id查询订单
        Orders order = orderMapper.getById(orderId);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果用户已经支付则要为用户退款
        if (OrdersConstant.HAVE_PAID.equals(order.getPayStatus())) {
            refund(order);
        }
        //将订单状态修改为“已取消”
        order.setStatus(OrdersConstant.CANCELLED);
        //为商家指定取消原因
        order.setCancelReason(cancelReason);
        //标记取消时间
        order.setCancelTime(LocalDateTime.now());
        //调用mapper修改
        orderMapper.update(order);

    }

    /**
     * 商家派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //通过id获取订单
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //当订单为“已接单”时才可执行派单操作
        if (!OrdersConstant.RECEIVED_ORDER.equals(order.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //执行接单操作,修改status字段
        orderMapper.delivery(id);
    }

    /**
     * 商家完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //通过id获取订单
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //当订单为“派送中”时才可执行完成订单操作
        if (!OrdersConstant.OUT_OF_DELIVERY.equals(order.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //执行接单操作,修改status字段与完成时间
        order.setStatus(OrdersConstant.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 用户催单
     */
    @Override
    public void reminder(Long id) {
        //查询订单
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map<Object, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 为用户退款
     *
     * @param order
     */
    private void refund(Orders order) {
        //获取用户支付金额
        BigDecimal amount = order.getAmount();
        //调用微信支付退款接口
        try {
            weChatPayUtil.refund(
                    order.getNumber(), //商户订单号
                    order.getNumber(), //商户退款单号
                    new BigDecimal(String.valueOf(amount)),//退款金额，单位 元
                    new BigDecimal(String.valueOf(amount)));//原订单金额
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //修改用户支付状态为退款
        order.setPayStatus(OrdersConstant.REFUND);
    }
}
